<?php
defined('IN_NWIDC') or exit('Access Invalid!');
header("content-Type: text/html; charset=UTF-8");

class zhifub2c{
    /*
     * 商户号
     * */
    private $merchant_code       = '';
    /*
     * 商户私钥
     * */
    private $merchant_private_key = '';
    /*
     * 商户公钥
     * */
    private $merchant_public_key  = '';
    /*
     * 智付公钥
     * */
    private $dinpay_public_key    = '';
    /**
     * 支付结果
     * return boolean
     */
    private $pay_result           = false;
    /*
     * 接口配置信息(array)
     * */
    private $request              = array();
    /*
     * 订单信息(array)
     * */
    private $order                = array();

    public function __construct($payment_info,$order_info){
        $this->zhifub2c($payment_info,$order_info);
    }
    public function zhifub2c($payment_info = array(),$order_info = array()){
        if(!empty($payment_info) and !empty($order_info)){

            $this->request	            = $payment_info;
            $this->order	            = $order_info;

            $this->merchant_code        = $this->request['payment_config']['merchant_code'];
            $this->merchant_private_key = preg_replace('/\s*/', '', trim($this->request['payment_config']['private_key']));
            $this->merchant_public_key  = preg_replace('/\s*/', '', trim($this->request['payment_config']['public_key']));
            $this->dinpay_public_key    = preg_replace('/\s*/', '', trim($this->request['payment_config']['dinpay_public_key']));
        }
    }

    public function submit(){

        $order_info = Model('order')->getOrderInfo([
            'pay_sn' => $this->order['pay_sn']
        ], ['order_goods']);

        $signStr= "";
        $product_name = "";

        foreach($order_info['extend_order_goods'] as $k => $v){
            if($k==0){
                $product_name .= $v['goods_name'];
            }else{
                $product_name .= '_'.$v['goods_name'];
            }
        }

        $parms = array(
            'sign'              => '',
            'merchant_code'     => $this->merchant_code,
            'service_type'      => "direct_pay",
            'interface_version' => "V3.0",
            'sign_type'         => "RSA-S",
            'input_charset'     => "UTF-8",
            'notify_url'        => "http://".$_SERVER['HTTP_HOST']."/shop/api/payment/zhifub2c/notify_url.php",
            'return_url'        => "http://".$_SERVER['HTTP_HOST']."/shop/api/payment/zhifub2c/return_url.php",
            'order_no'          => $order_info['order_sn'],
            'order_time'        => date( 'Y-m-d H:i:s' ,$order_info['add_time']),
            'order_amount'      => $order_info['order_amount'],
            'product_name'      => $product_name,
            'extra_return_param'=> $this->order['order_type'].'__'.$order_info['pay_sn'],
            'extend_param'      => 'customer_name^'.$order_info['receiver_name'].'|customer_idNumber^'.$order_info['idcard']
        );

        $signStr = $signStr."extend_param=".$parms['extend_param']."&";
        $signStr = $signStr."extra_return_param=".$parms['extra_return_param']."&";
        $signStr = $signStr."input_charset=".$parms['input_charset']."&";
        $signStr = $signStr."interface_version=".$parms['interface_version']."&";
        $signStr = $signStr."merchant_code=".$parms['merchant_code']."&";
        $signStr = $signStr."notify_url=".$parms['notify_url']."&";
        $signStr = $signStr."order_amount=".$parms['order_amount']."&";
        $signStr = $signStr."order_no=".$parms['order_no']."&";
        $signStr = $signStr."order_time=".$parms['order_time']."&";
        $signStr = $signStr."product_name=".$parms['product_name']."&";
        $signStr = $signStr."return_url=".$parms['return_url']."&";
        $signStr = $signStr."service_type=".$parms['service_type'];

        $merchant_private_key = "-----BEGIN PRIVATE KEY-----"."\r\n".wordwrap(trim($this->merchant_private_key),64,"\r\n",true)."\r\n"."-----END PRIVATE KEY-----";

        $merchant_private_key= openssl_get_privatekey($merchant_private_key);

        openssl_sign($signStr,$sign_info,$merchant_private_key,OPENSSL_ALGO_MD5);

        $sign = base64_encode($sign_info);

        $parms['sign'] = $sign;

        $html = '<html><head></head><body>';
        $html = '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">';
        $html .= '<form method="post" name="dinpayForm"  action="https://pay.dinpay.com/gateway?input_charset=UTF-8">
';
        foreach ($parms as $key => $val){
            $html .= "<input type='hidden' name='$key' value='$val' />";
        }
        $html .= '</form><script type="text/javascript">document.dinpayForm.submit();</script>';
        $html .= '</body></html>';
        echo $html;
        exit;

    }

    public function notify_verify(){

        $parms = array(
            'merchant_code'	       => $_POST["merchant_code"],
            'interface_version'    => $_POST["interface_version"],
            'sign_type'            => $_POST["sign_type"],
            'dinpaySign'           => base64_decode($_POST["sign"]),
            'notify_type'          => $_POST["notify_type"],
            'notify_id'            => $_POST["notify_id"],
            'order_no'             => $_POST["order_no"],
            'order_time'           => $_POST["order_time"],
            'order_amount'         => $_POST["order_amount"],
            'trade_status'         => $_POST["trade_status"],
            'trade_time'           => $_POST["trade_time"],
            'trade_no'             => $_POST["trade_no"],
            'extra_return_param'   => $_POST["extra_return_param"],
            'bank_seq_no'          => $_POST["bank_seq_no"]
        );


/////////////////////////////   参数组装  /////////////////////////////////
        /**
        除了sign_type dinpaySign参数，其他非空参数都要参与组装，组装顺序是按照a~z的顺序，下划线"_"优先于字母
         */


        $signStr = "";

        if($parms['bank_seq_no'] != ""){
            $signStr = $signStr."bank_seq_no=".$parms['bank_seq_no']."&";
        }

        if($parms['extra_return_param'] != ""){
            $signStr = $signStr."extra_return_param=".$parms['extra_return_param']."&";
        }
        $signStr = $signStr."interface_version=".$parms['interface_version']."&";
        $signStr = $signStr."merchant_code=".$parms['merchant_code']."&";
        $signStr = $signStr."notify_id=".$parms['notify_id']."&";
        $signStr = $signStr."notify_type=".$parms['notify_type']."&";
        $signStr = $signStr."order_amount=".$parms['order_amount']."&";
        $signStr = $signStr."order_no=".$parms['order_no']."&";
        $signStr = $signStr."order_time=".$parms['order_time']."&";
        $signStr = $signStr."trade_no=".$parms['trade_no']."&";
        $signStr = $signStr."trade_status=".$parms['trade_status']."&";
        $signStr = $signStr."trade_time=".$parms['trade_time'];

        //echo $signStr;

/////////////////////////////   RSA-S验证  /////////////////////////////////

        $dinpay_public_key = "-----BEGIN PUBLIC KEY-----"."\r\n".wordwrap(trim($this->dinpay_public_key),62,"\r\n",true)."\r\n"."-----END PUBLIC KEY-----";

        $dinpay_public_key = openssl_get_publickey($dinpay_public_key);

        $flag = openssl_verify($signStr,$parms['dinpaySign'],$dinpay_public_key,OPENSSL_ALGO_MD5);

///////////////////////////   响应“SUC CESS” /////////////////////////////

        if($flag){
            // echo"SUCCESS";
            if($_POST['trade_status']=='SUCCESS'){
                $this->pay_result = true;
                return true;
            }else{
                return false;
            }

        }else{
            //echo"Verification Error";
            return false;
        }

    }

    public function return_verify(){
        return $this->notify_verify();
    }

    /*
     * 取得订单支付状态，成功或失败
     * */
    public function getPayResult($param){
        return $this->pay_result;
    }
}

